package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.upmp.bean.McGrpInfo;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.BankLevelQuotalManagerMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.MerMCCInfo;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.exception.RedpException;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.ApiModel;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;

@Service
@Transactional
public class BankLevelQuotalManagerServiceImpl implements BankLevelQuotaManagetService{
    private final static Logger log = LoggerFactory.getLogger(BankLevelQuotalManagerServiceImpl.class);
        @Autowired
        private BankLevelQuotalManagerMapper bankLevelQuotalManagerMapper;
        @Autowired
        private   IUpmpOrganizationService upmpOrganizationService;
    @Autowired
    private MerGrpInfoService merGrpInfoService;
        @Autowired
        private IndustryInfoService industryInfoService;
        @Autowired
        private IBizTmpService bizTmpService;
        @Autowired
        private IBizHisService bizHisService;
        @Autowired
        private  IUpmpPrivilegeCheckService upmpPrivilegeCheckService;
        @Autowired
        private BTxnLimitCfgService bTxnLimitCfgService;

    private final String webNextUrl = "bizimpl/upmp/quota/bankLevelManager/BankLevelManagerInfo";

    private final String oprMenuId = "30000005";

    private final String oprMenuName = "风险管理:商户限额管理:商户组别限额管理";
/**
     * 获取 商户组别限额 配置list
     *
     * @return
     */
    @Override
    public List<BTxnLimitCfg> getBankLevelQuotaList(HttpServletRequest request) throws RedpException {
        List<BTxnLimitCfg> pageInfo = queryBankLevelQuotaList(request);
        return pageInfo;
    }
    private List<BTxnLimitCfg> queryBankLevelQuotaList(HttpServletRequest request) throws RedpException {
        String grpNo = request.getParameter("grpNo");
        String industryType = request.getParameter("industryType");
        String instId = request.getParameter("instId");
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);

//        boolean flag = user.isAdmin();
//        if (flag) {
//            instId = request.getParameter("instId");
//        }
//        if(!(flag)|| StringUtils.isBlank(instId)) {
//            instId = user.getInstId();
//        }
        if (StringUtils.isBlank(instId)) {
            log.error("获取用户多法人机构号时系统异常");
            throw new RedpException("获取用户多法人机构号时系统异常");
        }
        List<BTxnLimitCfg> bankQuotaList = new ArrayList<>();
        try {
            List<BTxnLimitCfg> btxnLimitCfgResultList = bankLevelQuotalManagerMapper.getBtxnLimitCfgResultList(instId,grpNo,industryType);
            if (btxnLimitCfgResultList.size() > 0) {
                bankQuotaList = mapBankLevelParam(btxnLimitCfgResultList);

            }
          return   bankQuotaList;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    private List<BTxnLimitCfg> mapBankLevelParam(List<BTxnLimitCfg> resultList) {
        ArrayList<BTxnLimitCfg> cfgVoList = new ArrayList<>();
        for(BTxnLimitCfg bTxnLimitCfg :resultList){

            BTxnLimitCfg txnLimitCfgVo = new BTxnLimitCfg();

            txnLimitCfgVo.setInstId(bTxnLimitCfg.getInstId());
            txnLimitCfgVo.setOprId(bTxnLimitCfg.getOprId());
            txnLimitCfgVo.setCrtOrgId(bTxnLimitCfg.getCrtOrgId());
            txnLimitCfgVo.setCreateTime(bTxnLimitCfg.getCreateTime());
            txnLimitCfgVo.setAuditStatus(bTxnLimitCfg.getAuditStatus());
            txnLimitCfgVo.setAuditRefuseReason(bTxnLimitCfg.getAuditRefuseReason());
            if (!bTxnLimitCfg.getStatus().equals(null)||bTxnLimitCfg.getStatus().equals("")){
                txnLimitCfgVo.setStatus(bTxnLimitCfg.getStatus());
            }
            txnLimitCfgVo.setIndustryType(bTxnLimitCfg.getIndustryType());
            txnLimitCfgVo.setIndustryName(bTxnLimitCfg.getIndustryName());
            txnLimitCfgVo.setGrpNo(bTxnLimitCfg.getGrpNo());
            txnLimitCfgVo.setGrpDesc(bTxnLimitCfg.getGrpDesc());

            txnLimitCfgVo.setNotDiffAcctId(bTxnLimitCfg.getNotDiffAcctId());
            txnLimitCfgVo.setLoanId(bTxnLimitCfg.getLoanId());
            txnLimitCfgVo.setCreditId(bTxnLimitCfg.getCreditId());
            txnLimitCfgVo.setLimitInst(bTxnLimitCfg.getLimitInst());
            txnLimitCfgVo.setLimitType(bTxnLimitCfg.getLimitType());
            txnLimitCfgVo.setDayLimitAmt(bTxnLimitCfg.getDayLimitAmt());
            txnLimitCfgVo.setMonthLimitAmt(bTxnLimitCfg.getMonthLimitAmt());
            txnLimitCfgVo.setSingleLimitLoanMaxAmt(bTxnLimitCfg.getSingleLimitLoanMaxAmt());
            txnLimitCfgVo.setDayLimitLoanAmt(bTxnLimitCfg.getDayLimitLoanAmt());
            txnLimitCfgVo.setMonthLimitLoanAmt(bTxnLimitCfg.getMonthLimitLoanAmt());
            txnLimitCfgVo.setSingleLimitCreditMaxAmt(bTxnLimitCfg.getSingleLimitCreditMaxAmt());
            txnLimitCfgVo.setDayLimitCreditAmt(bTxnLimitCfg.getDayLimitCreditAmt());
            txnLimitCfgVo.setMonthLimitCreditAmt(bTxnLimitCfg.getMonthLimitCreditAmt());

            cfgVoList.add(txnLimitCfgVo);
        }

        return cfgVoList;
    }
    /**
     * 新增商户组别MCC限额
     *
     * @param txnCfginfo
     * @param request
     */
    @Transactional(value = "transactionManager")
    public void addBankMCCquota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) throws RedpException {
        String industryType = txnCfginfo.getIndustryType();
        String grpNo = txnCfginfo.getGrpNo();
       /* if (StringUtils.isNotBlank(grpNo)&&StringUtils.isBlank(industryType)) {
            txnCfginfo.setLimitType("02");
            txnCfginfo.setLimitInst(txnCfginfo.getGrpNo());
        } else */if(StringUtils.isNotBlank(grpNo)&&StringUtils.isNotBlank(industryType)){
            txnCfginfo.setLimitType("03");
            txnCfginfo.setLimitInst(txnCfginfo.getIndustryType());
        }else {
            throw new RedpException("商户组别代码和商户MCC不能为空");
        }
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        String instId = "";
//        if(user.isAdmin()){
//            instId = request.getParameter("instId");
//            UpmpOrganization headOrg = upmpOrganizationService.getHeadOrgByCode(instId);
//            String crtOrgId = headOrg == null ? user.getOrgCode() : headOrg.getOrgCode();
//            txnCfginfo.setInstId(instId);
//            txnCfginfo.setCrtOrgId(crtOrgId);
//        }else {
//            instId = user.getInstId();
//            txnCfginfo.setInstId(instId);
//            txnCfginfo.setCrtOrgId(org.getOrgCode());
//        }
        instId=txnCfginfo.getInstId();
        txnCfginfo.setInstId(instId);
           txnCfginfo.setCrtOrgId(org.getOrgCode());
       //正确的 upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode()
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "bankLevelManager:add");
        //   AuthPrivilegeCheck privilegeCheckByPrivilegeCode = upmpOrganizationService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户组别限额管理:新增");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());//"01"新增待审核 02-新增审核通过
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setStatus("N");
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            saveTxnLimitCfgInfo(txnCfginfo);
            //保存零时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());
        } else {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());//"01"新增待审核 02-新增审核通过
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            saveTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo, null, BizOprEnum.OPR_ADD.getType());
        }
    }
    private void saveQuotaBizHis(BTxnLimitCfg txnCfginfo, BTxnLimitCfg oldTxnCfginfo, String bizOpr) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        List<BTxnLimitCfg> txnLimitCfgsOld = new ArrayList<>();
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        List<BTxnLimitCfg> txnLimitCfgs = coverBizData(txnCfginfo);
        if (BizOprEnum.OPR_ADD.getType().equals(bizOpr)) {
            for (BTxnLimitCfg bean : txnLimitCfgs) {
                txnLimitCfgsOld.add(new BTxnLimitCfg());
            }
        } else {
            txnLimitCfgsOld = coverBizData(oldTxnCfginfo);
        }
        List<String> realIds = new ArrayList<>();
        List<Object> entitys = new ArrayList<>();
        List<String> bizOprs = new ArrayList<>();
        List<Object> entitysOld = new ArrayList<>();
        for (BTxnLimitCfg bean : txnLimitCfgs) {
            realIds.add(CommonUtils.getUUID());
            entitys.add(bean);
            bizOprs.add(bizOpr);
        }
        for (BTxnLimitCfg bean : txnLimitCfgsOld) {

            entitysOld.add(bean);

        }


        //*？*/
        bizHisService.saveBizHisList(entitys, entitysOld, user, txnCfginfo.getInstId(), bizOprs,
                        txnLimitCfgs.get(0).getCreateTime(), oprMenuId, oprMenuName, realIds,null,null,null);
    }
    private void  saveTxnLimitCfgInfo (BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            String limitType = txnCfginfo.getLimitType();
            String instId = txnCfginfo.getInstId();
            String limitInst = txnCfginfo.getLimitInst();
            if (StringUtils.isBlank(limitType) || StringUtils.isBlank(instId) || StringUtils.isBlank(limitInst)) {
                log.error("请求数据有误:[{}]", limitType + "|" + instId + "|" + limitInst);
                throw new RedpException("请求数据有误:" + limitType + "|" + instId + "|" + limitInst);
            }
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("LIMIT_ACCT_TYPE",'*');
            queryWrapper.eq("limit_Type", limitType);
            queryWrapper.eq("inst_Id", instId);
            queryWrapper.eq("limit_Inst", limitInst);

            List resultListCount = bTxnLimitCfgService.list(queryWrapper);

            if (resultListCount.size() > 0) {
                log.error("限额信息已存在:[{}]", txnCfginfo.getLimitInst());
                throw new RedpException(txnCfginfo.getLimitInst() + "限额信息已存在");
            }

            UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);

            //限额
            BTxnLimitCfg bTxnLimitCfg=new BTxnLimitCfg();
            bTxnLimitCfg.setInstId(instId);
            bTxnLimitCfg.setLimitType(txnCfginfo.getLimitType());
            bTxnLimitCfg.setLimitInst(txnCfginfo.getLimitInst());
            bTxnLimitCfg.setLimitAcctType("*"); //"*" 不分账户类型
            bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitMaxAmt());
            bTxnLimitCfg.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
            bTxnLimitCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());
            bTxnLimitCfg.setStatus(txnCfginfo.getStatus());
            bTxnLimitCfg.setAuditStatus(txnCfginfo.getAuditStatus());
            bTxnLimitCfg.setOprId(txnCfginfo.getOprId());
            bTxnLimitCfg.setCrtOrgId(txnCfginfo.getCrtOrgId());
            bTxnLimitCfg.setCreateTime(txnCfginfo.getCreateTime());
            bTxnLimitCfg.setId(txnCfginfo.getNotDiffAcctId());
            bTxnLimitCfgService.save(bTxnLimitCfg);

            //借记限额
            bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            bTxnLimitCfg.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            bTxnLimitCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            bTxnLimitCfg.setLimitAcctType("20");//20-借记账户(包括本行、他行借记账户)  21-贷记账户(包括本行、他行贷记账户)
            bTxnLimitCfg.setId(txnCfginfo.getLoanId());
            bTxnLimitCfgService.save(bTxnLimitCfg);

            //贷记限额
            bTxnLimitCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            bTxnLimitCfg.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            bTxnLimitCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            bTxnLimitCfg.setLimitAcctType("21");
            bTxnLimitCfg.setId(txnCfginfo.getCreditId());
            bTxnLimitCfgService.save(bTxnLimitCfg);
            return;
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }

    //保存临时表
    private void saveBizTmp(BTxnLimitCfg txnCfginfo, String oprType) throws RedpException {
        //主记录key
        String uuid =CommonUtils.getUUID();
        if (StringUtils.isNotBlank(oprType) && !(BizOprEnum.OPR_ADD.getType().equals(oprType))) {
            BizTmp tmp = bizTmpService.getBizTmpDetail(txnCfginfo.getNotDiffAcctId());

            if (null != tmp && StringUtils.isNotBlank(tmp.getMasterKey())) {
                uuid = tmp.getMasterKey();
            }

        }
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        List<BTxnLimitCfg> TxnDatalist = coverBizData(txnCfginfo);
        List<BizTmp> bizTmpList = new ArrayList<>();
        for (BTxnLimitCfg txnLimitCfg : TxnDatalist) {
            BizTmp tmp = coverBizTmp(txnLimitCfg, oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnLimitCfg.getAuditStatus(), webNextUrl);
            String bizData = JSON.toJSONString(txnLimitCfg);
            if (bizData.length() > 12000) {
                throw new RedpException("业务数据过长，请联系管理员！");
            }
            String bizData1;
            String bizData2 = "";
            String bizData3 = "";
            if (bizData.length() > 4000) {
                bizData1 = bizData.substring(0, 3999);
                bizData2 = bizData.substring(4000);
            } else {
                bizData1 = bizData;
            }
            if (bizData2.length() > 4000) {
                bizData2 = bizData2.substring(0, 3999);
                bizData3 = bizData.substring(8000);
            }
            tmp.setMchntNo(null);
            tmp.setMchntName(null);
            tmp.setTermNo(null);
            tmp.setBizData1(bizData1);
            tmp.setBizData2(bizData2);
            tmp.setBizData3(bizData3);
            tmp.setDetailFlag("Y");
            tmp.setMasterKey(uuid);
            tmp.setRealId(txnLimitCfg.getId());
            bizTmpList.add(tmp);
        }
        BizTmp bizTmp = coverBizTmp(TxnDatalist.get(0), oprType, oprMenuId, oprMenuName, org.getOrgCode(), user.getInstId(), txnCfginfo.getBizStatus(), txnCfginfo.getAuditStatus(), webNextUrl);
        bizTmp.setBizData1("明细有" + bizTmpList.size() + "条");
        bizTmp.setMchntNo(null);
        bizTmp.setMchntName(null);
        bizTmp.setTermNo(null);
        bizTmp.setRealId(uuid);
        bizTmp.setDetailFlag("N");
        bizTmpList.add(bizTmp);
        for (BizTmp bean:bizTmpList) {
            bizTmpService.save(bean);
        }

    }

    private List<BTxnLimitCfg> coverBizData(BTxnLimitCfg txnCfginfo) {
        List<BTxnLimitCfg> txnLimitCfgs = new ArrayList<>();
        BTxnLimitCfg notDiff = new BTxnLimitCfg();
        notDiff.setSingleLimitMaxAmt("");
        notDiff.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
        notDiff.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());
        notDiff.setStatus(txnCfginfo.getStatus());
        notDiff.setAuditStatus(txnCfginfo.getAuditStatus());
        notDiff.setOprId(txnCfginfo.getOprId());
        notDiff.setCreateTime(txnCfginfo.getCreateTime());
        notDiff.setLastOprId(txnCfginfo.getLastOprId());
        notDiff.setLastUpdateTime(txnCfginfo.getLastUpdateTime());
        notDiff.setLimitAcctType("*");
        notDiff.setInstId(txnCfginfo.getInstId());
        notDiff.setLimitType(txnCfginfo.getLimitType());
        notDiff.setLimitInst(txnCfginfo.getLimitInst());
        notDiff.setId(txnCfginfo.getNotDiffAcctId());
        txnLimitCfgs.add(notDiff);


        BTxnLimitCfg credCfg = new BTxnLimitCfg();
        credCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
        credCfg.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
        credCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
        credCfg.setStatus(txnCfginfo.getStatus());
        credCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        credCfg.setOprId(txnCfginfo.getOprId());
        credCfg.setCreateTime(txnCfginfo.getCreateTime());
        credCfg.setLimitAcctType("21");
        credCfg.setInstId(txnCfginfo.getInstId());
        credCfg.setLimitType(txnCfginfo.getLimitType());
        credCfg.setLimitInst(txnCfginfo.getLimitInst());
        credCfg.setId(txnCfginfo.getCreditId());
        txnLimitCfgs.add(credCfg);



        BTxnLimitCfg loanCfg = new BTxnLimitCfg();
        loanCfg.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
        loanCfg.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
        loanCfg.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
        loanCfg.setStatus(txnCfginfo.getStatus());
        loanCfg.setAuditStatus(txnCfginfo.getAuditStatus());
        loanCfg.setOprId(txnCfginfo.getOprId());
        loanCfg.setCreateTime(txnCfginfo.getCreateTime());
        loanCfg.setLimitAcctType("20");
        loanCfg.setInstId(txnCfginfo.getInstId());
        loanCfg.setLimitType(txnCfginfo.getLimitType());
        loanCfg.setLimitInst(txnCfginfo.getLimitInst());
        loanCfg.setId(txnCfginfo.getLoanId());
        txnLimitCfgs.add(loanCfg);


        return txnLimitCfgs;
    }
    private BizTmp coverBizTmp(BTxnLimitCfg entity, String bizOpr, String menuId, String menuName, String orgCode, String instId, String ruleStatus, String auditStatus, String webNextUrlStr) {
        BizTmp bizTmp = new BizTmp();
        //英文名字
        String ename = entity.getClass().getAnnotation(TableName.class).value().toLowerCase(Locale.ROOT);
        //中文名字
        String cname = entity.getClass().getAnnotation(ApiModel.class).description();
        bizTmp.setRealId(entity.getId());
        bizTmp.setBizData1("");
        bizTmp.setBizData2("");
        bizTmp.setBizData3("");
        bizTmp.setBizOpr(bizOpr);
        bizTmp.setOprId(entity.getOprId());
        bizTmp.setCreateTime(entity.getCreateTime());
        bizTmp.setLastOprId(entity.getLastOprId());
        bizTmp.setLastUpdateTime(entity.getLastUpdateTime());
        bizTmp.setOprMenuId(menuId);
        bizTmp.setOprMenuName(menuName);
        bizTmp.setOprTableCname(cname);
        bizTmp.setOprTableEname(ename);
        bizTmp.setManageInstId(orgCode);
        bizTmp.setInstId(instId);
        bizTmp.setBizStatus(ruleStatus);
        bizTmp.setAuditStatus(auditStatus);
        bizTmp.setWebNextUrl(webNextUrlStr);

        return bizTmp;
    }
    /**
     * 获取限额详情
     */
    public BTxnLimitCfg getBankLevelQuotaInfo(BTxnLimitCfg request) throws RedpException {
        try {
            String notDiffAcctId = request.getNotDiffAcctId();
            String creditId = request.getCreditId();
            String loanId = request.getLoanId();
            if (StringUtils.isBlank(notDiffAcctId) || StringUtils.isBlank(creditId) || StringUtils.isBlank(loanId)) {
                log.error("请求数据有误");
                throw new RedpException("请求数据有误");
            }

            List<BTxnLimitCfg> resultList = bankLevelQuotalManagerMapper.getBankLevelQuotaInfos(notDiffAcctId, creditId, loanId);
            if (null == resultList || resultList.size() > 1) {
                throw new RedpException("限额详情数据获取失败");
            }
            List<BTxnLimitCfg> bankQuotaList = mapBankLevelParam(resultList);

            return bankQuotaList.get(0);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 停用商户组别限额管理
     *
     * @param
     */
    @Transactional(value = "transactionManager")
    public void stopBankMCCquota(HttpServletRequest request, BTxnLimitCfg req) throws RedpException {
        BTxnLimitCfg txnCfginfo = getBankLevelQuotaInfo(req);


       UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(req.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());

        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "bankLevelManager:stop");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo, oldData);

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {

            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());//21-停用待审核
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_STOP.getType());
        } else {
            txnCfginfo.setStatus("N"); //Y 启用 N停用
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());//22-停用审核通过
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo, oldData, BizOprEnum.OPR_STOP.getType());
        }
    }
    private void updateTxnLimitCfgAuthStatus(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {
            //不分账户 终端限额
           // Query query = this.getEntityManager().createNativeQuery(sql.toString());
            QueryWrapper query=new QueryWrapper();
            query.eq("id",  txnCfginfo.getNotDiffAcctId());

            txnCfginfo.setStatus(txnCfginfo.getStatus());
            txnCfginfo.setAuditStatus( txnCfginfo.getAuditStatus());
            txnCfginfo.setLastOprId( txnCfginfo.getLastOprId());
            txnCfginfo.setLastUpdateTime(txnCfginfo.getLastUpdateTime());
            txnCfginfo.setAuditRefuseReason(txnCfginfo.getAuditRefuseReason());
         bTxnLimitCfgService.saveOrUpdate(txnCfginfo, query);


            //贷记
            QueryWrapper queryCr = new QueryWrapper();
          queryCr.eq("id", txnCfginfo.getCreditId());//20-借记账户(包括本行、他行借记账户) 21-贷记账户(包括本行、他行贷记账户)
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            bTxnLimitCfgService.saveOrUpdate(txnCfginfo, queryCr);

            //借记
            QueryWrapper queryLon = new QueryWrapper();
            queryLon.eq("id",  txnCfginfo.getLoanId());//20-借记账户(包括本行、他行借记账户) 21-贷记账户(包括本行、他行贷记账户)
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            bTxnLimitCfgService.saveOrUpdate(txnCfginfo, queryLon);

        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 启用商户组别限额管理
     *
     * @param
     */
    @Transactional(value = "transactionManager")
    public void startBankMCCquota(HttpServletRequest request, BTxnLimitCfg req) throws RedpException {
        BTxnLimitCfg txnCfginfo = getBankLevelQuotaInfo(req);
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(req.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "bankLevelManager:use");

        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo, oldData);

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {

            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_USE.getType());
        } else {
            txnCfginfo.setStatus("Y"); //Y 启用 N停用
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());//
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo, oldData, BizOprEnum.OPR_USE.getType());
        }
    }
    /**
     * 注销商户组别限额管理
     *
     * @param
     */
    @Transactional(value = "transactionManager")
    public void deleteBankMCCquota(HttpServletRequest request, BTxnLimitCfg req) throws RedpException {
        BTxnLimitCfg txnCfginfo = getBankLevelQuotaInfo(req);
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(req.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "bankLevelManager:cancel");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = new BTxnLimitCfg();
        BeanUtils.copyProperties(txnCfginfo, oldData);

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {

            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());//41-修改待审42-修改审核通过
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_CANCEL.getType());
        } else {

            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());//"01"新增待审核 02-新增审核通过
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            txnCfginfo.setStatus("N");
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo, oldData, BizOprEnum.OPR_CANCEL.getType());
        }
    }
    /**
     * 修改商户组别MCC限额
     *
     * @param txnCfginfo
     * @param request
     */
    @Transactional(value = "transactionManager")
    public void editBankMCCquota(BTxnLimitCfg txnCfginfo, HttpServletRequest request) throws RedpException {
        String limitType = txnCfginfo.getLimitType();
        if ("02".equals(limitType)) {

            txnCfginfo.setLimitInst(txnCfginfo.getGrpNo());
        } else if ("03".equals(limitType)) {

            txnCfginfo.setLimitInst(txnCfginfo.getIndustryType());
        } else {
            throw new RedpException("限额类型不匹配" + limitType);
        }

        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        UpmpOrganization org = upmpOrganizationService.getOrgByCode(user.getOrgCode(), user.getInstId());
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "bankLevelManager:edit");
      //  AuthPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(txnCfginfo.getInstId(), "商户组别限额管理:修改");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }
        BTxnLimitCfg oldData = getBankLevelQuotaInfo(txnCfginfo);
        txnCfginfo.setStatus(oldData.getStatus());
        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());//41-修改待审42-修改审核通过
            txnCfginfo.setLastOprId(user.getOprId());
            txnCfginfo.setLastUpdateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));

            //修正式表
            updateTxnLimitCfgAuthStatus(txnCfginfo);
            //修改临时表
            saveBizTmp(txnCfginfo, BizOprEnum.OPR_UPDATE.getType());
        } else {

            txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
            txnCfginfo.setOprId(user.getOprId());
            txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
            //保存正式表
            updateTxnLimitCfgInfo(txnCfginfo);
            //保存历史表
            saveQuotaBizHis(txnCfginfo, oldData, BizOprEnum.OPR_UPDATE.getType());
        }
    }
    private void updateTxnLimitCfgInfo(BTxnLimitCfg txnCfginfo) throws RedpException {
        try {

            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitAmt());
            txnCfginfo.setStatus(txnCfginfo.getStatus());
            txnCfginfo.setAuditStatus(txnCfginfo.getAuditStatus());
            txnCfginfo.setLastOprId(txnCfginfo.getLastOprId());
            txnCfginfo.setLastUpdateTime(txnCfginfo.getLastUpdateTime());
            txnCfginfo.setAuditReason(txnCfginfo.getAuditRefuseReason());
            txnCfginfo.setId(txnCfginfo.getNotDiffAcctId());
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("id", txnCfginfo.getNotDiffAcctId());
            bTxnLimitCfgService.update(txnCfginfo,queryWrapper);

            //借记限额
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitLoanMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitLoanAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitLoanAmt());
            queryWrapper.clear();
            queryWrapper.eq("id", txnCfginfo.getLoanId());
            bTxnLimitCfgService.update(txnCfginfo,queryWrapper);

            //贷记限额
            txnCfginfo.setSingleLimitMaxAmt(txnCfginfo.getSingleLimitCreditMaxAmt());
            txnCfginfo.setDayLimitAmt(txnCfginfo.getDayLimitCreditAmt());
            txnCfginfo.setMonthLimitAmt(txnCfginfo.getMonthLimitCreditAmt());
            queryWrapper.clear();
            queryWrapper.eq("id", txnCfginfo.getCreditId());
            bTxnLimitCfgService.update(txnCfginfo, queryWrapper);

        } catch (Exception e) {
            // TODO: handle exception
            log.error("交易出现异常，异常信息：" + e.getMessage());
            throw new RedpException("交易出现异常，异常信息：" + e.getMessage());
        }
    }
    /**
     * 获取 所有的商户组别list
     */
    public List<McGrpInfo> getMcGrpList() {
        List<Map> merGrpInfos =merGrpInfoService.getMcGrpList("");
        List<McGrpInfo> mcGrpInfnList = new ArrayList<>();
        merGrpInfos.forEach((e) -> {
            McGrpInfo mcGrpInfo = new McGrpInfo();
            mcGrpInfo.setGrpNo(e.get("GRPNO").toString());
            mcGrpInfo.setGrpDesc(e.get("GRPDESC").toString());
            mcGrpInfnList.add(mcGrpInfo);
        });
        return mcGrpInfnList;
    }
    public List<IndustryInfo> getMCCList(){
        List<IndustryInfo> all = industryInfoService.list();
        return all;
    }
    /**
     * 获取 商户MCCList
     */
    public List<MerMCCInfo> getMCCList(String grpNo) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("grp_no", grpNo);
        List<IndustryInfo> industryInfos = industryInfoService.list(queryWrapper);
        List<MerMCCInfo> merMccList = new ArrayList<>();
        industryInfos.forEach((e) -> {
            MerMCCInfo mccInfo = new MerMCCInfo();
            mccInfo.setIndustryType(e.getIndustryType());
            mccInfo.setIndustryName(e.getIndustryName());
            merMccList.add(mccInfo);
        });
        return merMccList;
    }

    @Transactional(value = "transactionManager")
    public void batchUploadBankQuotal(ArrayList<BTxnLimitCfg> bankLevelQuotaList,String instId) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(instId);
        UpmpPrivilegeCheck privilegeCheckByPrivilegeCode = upmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "bankLevelManager:import");

       // AuthPrivilegeCheck privilegeCheckByPrivilegeCode = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "商户组别限额管理:导入");
        if (null == privilegeCheckByPrivilegeCode) {
            throw new RedpException("获取审核信息失败");
        }

        boolean checked = BusinessContainer.YES.equals(privilegeCheckByPrivilegeCode.getChecked());
        if (checked) {
            bankLevelQuotaList.forEach((e) -> {
                try {
                    uploadIsChecked(e);
                } catch (RedpException redpException) {
                    redpException.printStackTrace();
                }
            });
        } else {

            bankLevelQuotaList.forEach((e) -> {
                try {
                    uploadNotChecked(e);
                } catch (RedpException redpException) {
                    redpException.printStackTrace();
                }
            });
        }
    }

    private void uploadIsChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        String grpNo = txnCfginfo.getGrpNo();
        if (StringUtils.isNotBlank(grpNo)&&StringUtils.isBlank(industryType)) {
            txnCfginfo.setLimitType("02");
            txnCfginfo.setLimitInst(txnCfginfo.getGrpNo());
        } else if(StringUtils.isNotBlank(grpNo)&&StringUtils.isNotBlank(industryType)){
            txnCfginfo.setLimitType("03");
            txnCfginfo.setLimitInst(txnCfginfo.getIndustryType());
        }else {
            throw new RedpException("商户组别代码不能为空");
        }
        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        //     txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("N"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
        txnCfginfo.setOprId(user.getOprId());
        //      txnCfginfo.setCrtOrgId(user.getOrgCode());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveTxnLimitCfgInfo(txnCfginfo);
        //保存零时表
        saveBizTmp(txnCfginfo, BizOprEnum.OPR_ADD.getType());

    }

    private void uploadNotChecked(BTxnLimitCfg txnCfginfo) throws RedpException {
        UpmpUserInfoVO user = RedpUpmpUtil.getCurrentUser(txnCfginfo.getInstId());
        String industryType = txnCfginfo.getIndustryType();
        String grpNo = txnCfginfo.getGrpNo();
        if (StringUtils.isNotBlank(grpNo)&&StringUtils.isBlank(industryType)) {
            txnCfginfo.setLimitType("02");
            txnCfginfo.setLimitInst(txnCfginfo.getGrpNo());
        } else if(StringUtils.isNotBlank(grpNo)&&StringUtils.isNotBlank(industryType)){
            txnCfginfo.setLimitType("03");
            txnCfginfo.setLimitInst(txnCfginfo.getIndustryType());
        }else {
            throw new RedpException("商户组别代码不能为空");
        }
        //设置数据Id
        txnCfginfo.setNotDiffAcctId(CommonUtils.getUUID());
        txnCfginfo.setCreditId(CommonUtils.getUUID());
        txnCfginfo.setLoanId(CommonUtils.getUUID());
        //    txnCfginfo.setInstId(user.getInstId());

        txnCfginfo.setStatus("Y"); //Y 启用 N停用
        txnCfginfo.setBizStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
        txnCfginfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
        txnCfginfo.setOprId(user.getOprId());
        //    txnCfginfo.setCrtOrgId(user.getOrgCode());
        txnCfginfo.setCreateTime(DateUtils.formatDate(new Date(), DateUtils.DEFAULT_TIME_FORMAT));
        //保存正式表
        saveTxnLimitCfgInfo(txnCfginfo);
        //保存历史表
        saveQuotaBizHis(txnCfginfo, null, BizOprEnum.OPR_ADD.getType());
    }

    @Override
    public boolean saveBatch(Collection<T> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<T> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        return false;
    }

    @Override
    public T getOne(Wrapper<T> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper<T> queryWrapper) {
        return null;
    }

    @Override
    public <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

    @Override
    public BaseMapper<T> getBaseMapper() {
        return null;
    }
}
